﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using nwrole.lib;

namespace nwrole.service
{
    internal class ServiceManagement : IDisposable, IServiceManager
    {
        public Guid GetIdentifier ()
        {
            return manager.GetIdentifier();
        }

        public Result InstantiatePlugin (Plugin plugin, Solution solution, Solution.Service service, Solution.Instance instance)
        {
            return manager.InstantiatePlugin(plugin, solution, service, instance);
        }

        public Result KillInstance (Guid instanceId)
        {
            return manager.KillInstance(instanceId);
        }

        #region Common
        private IServiceManager manager;

        public ServiceManagement (nwrole.lib.Solution.Service service)
        {
            try
            {
                EndpointAddress address = new EndpointAddress("net.tcp://localhost:" + service.ManagementPort.ToString() + "/" + service.Id.ToString("N"));
                NetTcpBinding binding = new NetTcpBinding();
                binding.ReceiveTimeout = new TimeSpan(0, 0, 120);
                binding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
                binding.MaxReceivedMessageSize = 2147483647;
                ChannelFactory<IServiceManager> facory = new ChannelFactory<IServiceManager>(binding, address);
                facory.Credentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
                manager = facory.CreateChannel();
            }
            catch (Exception exception)
            {
                EventLogger.LogException("+ServiceManagement", exception);
            }
        }

        public void Dispose ()
        {
            try
            {
                ((IClientChannel)manager).Close(TimeSpan.FromSeconds(30));
                ((IClientChannel)manager).Dispose();
            }
            catch (Exception exception)
            {
                EventLogger.LogException("ServiceManagement.Dispose", exception);
            }
        }

        #endregion
    }
}
